import { addparam } from '@/apiList/addParam'
import { local, session } from '@/utils/jcore/storage'
import { getProxyPath } from '@/config/proxyPath'
import { osTenantId } from '@/config/app'
import BaseQuickRequest from '@/utils/request/BaseQuickRequest'
import { DefaultConfig, ApiControlConfig } from '@/utils/request/DefaultConfig'

/**添加字段 */
function addObjKey(data, addKey) {
  const userInfo = local.get('userInfo')
  for (let key in data) {
    if (Object.prototype.toString.call(data[key]) == '[object Object]') {
      data[key][addKey] = userInfo.overallUserID
    }
  }
  return data
}
/**
 * AxiosUtil 请求重写
 */
class AxiosUtil extends BaseQuickRequest {
  postJson(url, data = {}, callBack) {
    const user = local.get('userInfo')
    return this.adapter({
      url,
      data: addparam(data),
      method: 'post',
      headers: {
        osTenantId,
        'User-Identity': user ? user.sysOrganizeUserId : '',
        'X-Authorization': session.get('token') || '',
        'content-type': 'application/json;charset=UTF-8'
      }
    }).then(callBack)
  }
  postAddJson(url, data = {}, callBack) {
    return this.postJson(url, addObjKey(data, 'creator'), callBack)
  }
  postUpdateJson(url, data = {}, callBack) {
    return this.postJson(url, addObjKey(data, 'updater'), callBack)
  }
}

/**
 * 创建请求实例
 * @param config 基础配置
 * @param apiControl 请求操作控制
 * @returns
 */
export function createRequest(config, apiControl) {
  const c = Object.assign({}, DefaultConfig, config)
  const a = Object.assign({}, ApiControlConfig, apiControl)
  return new AxiosUtil(c, a)
}

const baseURL = getProxyPath('apiC')
export const axiosUtil = createRequest({ baseURL })
